package com.milling.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class SocketUtils implements AutoCloseable{
    private static final Logger logger = LoggerFactory.getLogger(SocketUtils.class);

    public String socketIp = "";
    public int socketPort = 0;


    //    public String socketIp = "";
//    public int socketPort = 0;
    private Socket socket; // 添加Socket成员变量
    private OutputStream outputStream; // 添加OutputStream成员变量

    public SocketUtils(String socketIp, int socketPort) {
        this.socketIp = socketIp;
        this.socketPort = socketPort;
        try {
            // 初始化Socket连接
            this.socket = new Socket(socketIp, socketPort);
            this.outputStream = this.socket.getOutputStream();
        } catch (IOException e) {
            logger.error("初始化Socket连接失败: " + this.socketIp + "/" + e.getMessage());
            e.printStackTrace();
        }
    }

    public void sendMessage(String message) {
        try {
            if (outputStream != null) {
                outputStream.write(message.getBytes("UTF-8"));
                outputStream.flush();
            } else {
                logger.error("输出流未初始化");
            }
        } catch (IOException e) {
            logger.error("发送消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 断开连接方法
    public void disconnect() {
        try {
            if (outputStream != null) {
                outputStream.close();
                outputStream = null;
            }
            if (socket != null && !socket.isClosed()) {
                socket.close();
                socket = null;
            }
//            logger.info("Socket连接已断开");
        } catch (IOException e) {
            logger.error("断开连接时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 销毁方法
    public void destroy() {
        disconnect(); // 先断开连接
        // 这里可以添加其他清理资源的代码
//        logger.info("SocketUtils已销毁");
    }

    @Override
    public void close() {
        disconnect();
    }
}
